package util

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

// GetAssetsPath 生成单个 Toc 的附件目录
func GetAssetsPath(downloadTocPath string) (baseDir, assetsPath string) {
	// Toc 所处目录名
	baseDir = filepath.Base(downloadTocPath)

	assetsPath = filepath.Join(downloadTocPath[:strings.LastIndex(downloadTocPath, baseDir)],
		fmt.Sprintf("%s.assets", baseDir))

	stat, _ := os.Stat(assetsPath)
	if stat == nil || !stat.IsDir() {
		os.MkdirAll(assetsPath, os.ModePerm)
	}

	return
}

func PathJoin(elem ...string) (res string) {
	paths := make([]string, len(elem))
	for _, e := range elem {
		e = EscapeFileName(e)
		paths = append(paths, e)
	}
	res = filepath.Join(paths...)
	return
}

// EscapeFileName 文件路径名转为安全内容
func EscapeFileName(fileName string) (res string) {
	// 文件名不能包含 / \ : * ? " < > |

	// 将能替换的替换掉，不能替换的改为 _
	res = strings.ReplaceAll(fileName, "/", "⧸")

	res = strings.ReplaceAll(res, "\\", "⧸")

	res = strings.ReplaceAll(res, ":", "：")

	res = strings.ReplaceAll(res, "*", "_")

	res = strings.ReplaceAll(res, "?", "？")

	res = strings.ReplaceAll(res, "\"", "'")

	res = strings.ReplaceAll(res, "<", "《")
	res = strings.ReplaceAll(res, ">", "》")
	res = strings.ReplaceAll(res, "|", "_")

	return
}
